#!/usr/bin/python
# -*- coding: utf-8 -*-

from PyQt4 import QtCore, QtGui
from PythonUI.Ui_Page7 import Ui_Page7
import os
import sys
import re
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import Qt
from Main import *
from echelle import *
from mesure import *
from gestion import *
from carto import *
from DAC.MesureDAC import Mesure
from DAC.ConfigWifiDAC import ConfigWifi
from DAC.ListWifiDAC import ListWifi
from DAC.PerfWifiDAC import PerfWifi

globals()["campagne"] = 0

class Page7(Ui_Page7,QtGui.QDialog):
    """
    Page ou on effectue les mesures
    """
    def __init__(self,session):
        """
        Fonction d'initialisation
        """
        self.app = QtGui.QApplication(sys.argv)
        QtGui.QDialog.__init__(self)
        self.session=session
        self.retour=0
        self.parametre={}
        self.config={}
        self.oldx = 0
        self.oldy = 0
        self.nbMesure=0
        os.system("touch ~/.GWA/nbMesure")
        self.filename = ""
        dicosalle={}
        dicobatiment={}
        self.dicocampagne={}   
        self.dicoiperftcp={}
        self.dicoiperfudp={}
        expr=re.compile('[a-zA-Z]')        
        fichier=open(os.path.expanduser('~') + '/.GWA/dicosalle','r')
        for line in fichier.readlines():
            if expr.findall(line):
                dicosalle[line.split(':')[0].split('\n')[0]]=line.split(':')[1].split('\n')[0]
        fichier.close()
        fichier=open(os.path.expanduser('~') + '/.GWA/dicocampagne','r')
        for line in fichier.readlines():
            if expr.findall(line):
                self.dicocampagne[line.split(':')[0].split('\n')[0]]=line.split(':')[1].split('\n')[0]
        fichier.close()
        globals()["campagne"] = self.dicocampagne
        if(os.path.isfile(os.path.expanduser('~') + '/.GWA/dicoiperftcp')):
	    fichier=open(os.path.expanduser('~') + '/.GWA/dicoiperftcp','r')
            for line in fichier.readlines():
                if expr.findall(line):
                    self.dicoiperftcp[line.split(':')[0].split('\n')[0]]=line.split(':')[1].split('\n')[0]
            fichier.close()
        if(os.path.isfile(os.path.expanduser('~') + '/.GWA/dicoiperfudp')):
            fichier=open(os.path.expanduser('~') + '/.GWA/dicoiperfudp','r')
            for line in fichier.readlines():
                if expr.findall(line):
                    self.dicoiperfudp[line.split(':')[0].split('\n')[0]]=line.split(':')[1].split('\n')[0]
            fichier.close()
        fichier=open(os.path.expanduser('~') + '/.GWA/dicobatiment','r')
        for line2 in fichier.readlines():
            if expr.findall(line2):
                dicobatiment[line2.split(':')[0].split('\n')[0]]=line2.split(':')[1].split('\n')[0]
        fichier.close()
        dicodico={'batiment':dicobatiment,'salle':dicosalle}     
        self.dictionnaire = dicodico

    def actualise_image(self):
        """
        Actualisation du label plan
        """
        regex=re.compile('(.*)/(.*)\..*')
        result_regex=regex.findall(self.dictionnaire["salle"]["url_plan"])    
        self.fichierpng=result_regex[0][1]
        objImg = QtGui.QImage(os.path.expanduser('~')+'/.GWA/'+self.fichierpng+str("_mesure.png"))
        self.label_plan.setPixmap(QtGui.QPixmap.fromImage(objImg.scaled(377,250,Qt.KeepAspectRatio,Qt.SmoothTransformation)))
        self.label_plan.setVisible(True)

    def suivant(self):
        """
        Fonction appele lors de la validation du bouton 'Ok'
        """     
        #On dessine nos mesures sur le plan de la salle avec le bon gradient
        final = Dessin3("")
        final.dessiner(self.dictionnaire["salle"]["url_plan"],self.ech,int(globals()["campagne"]["step"]))
        file=open(os.path.expanduser('~') + '/.GWA/nbMesure','a')
        file.write(str(self.nbMesure))
        file.close()
        self.close()
        obj8=Main()
        obj8.func8(self.config)

    def affich(self,param):
        """
        Affichage de la fenetre
        """
        self.setupUi(self)
        self.show()
        sys.exit(self.app.exec_())

    def precedent(self):
        """
        Fonction appele lors de la selection du bouton 'Annuler'
        """
        if self.dicoiperftcp == {} and self.dicoiperfudp == {}:
            self.close()
            os.system("./Main.py 5")
        else:
            self.close()
            os.system("./Main.py 6")

    def avance(self):
        """
        Selection du point de mesure suivant
        """
        #Il faut deja avoir selectionne un point de depart
        if (self.comboBox_X.currentText() != '...' and self.comboBox_Y.currentText() != '...' and self.comboBox_Z.currentText() != '...'):
            #On regarde ou on se trouve et jusqu'ou on peut aller
            position_initiale_X=self.comboBox_X.currentIndex()
            position_max_X=self.comboBox_X.count() - 1
            position_initiale_Y=self.comboBox_Y.currentIndex()  
            position_max_Y=self.comboBox_Y.count() - 1
            #Si je suis pas au max de mon combobox Y, j'augmente
            if (position_initiale_Y < position_max_Y):
                self.comboBox_Y.setCurrentIndex(position_initiale_Y+1)
            #Sinon et si je suis pas au max mon combobox X, j'augmente et je reset la combobox Y
            elif (position_initiale_X < position_max_X):
                self.comboBox_X.setCurrentIndex(position_initiale_X+1)
                self.comboBox_Y.setCurrentIndex(1)
            #sinon je fais rien
            else:
                pass
                
    def calculCoord(self):
        """
        On dessine les croix sur le plan
        """
        ratio = calculEchelle(self.dictionnaire,"salle")
        self.ech = calculPoints(int(globals()["campagne"]["step"]))
        dess = Dessin("")
        dess.dessiner(self.dictionnaire["salle"]["url_plan"],self.ech,int(globals()["campagne"]["step"]))
        self.actualise_image()
        self.miseAJour()

    def miseAJour(self):
        """
        Prise de mesure
        """
        dess2 = Dessin("")
        if (self.comboBox_X.currentText() != '' and self.comboBox_Y.currentText() != '' and self.comboBox_Z.currentText() != ''):
            if (self.comboBox_X.currentText() != '...' and self.comboBox_Y.currentText() != '...' and self.comboBox_Z.currentText() != '...'):
		
                x = int(self.comboBox_X.currentText())
                y = int(self.comboBox_Y.currentText())
                z = int(self.comboBox_Z.currentText())

            	for element in self.ech:
                    if (x != 0 and y != 0):
                        if ((element["x_step"] == x) and (element["y_step"] == y)):
                            element["shape"] = "rond"
                            dess2.dessiner(self.dictionnaire["salle"]["url_plan"],self.ech,int(globals()["campagne"]["step"]))            
                            dess2.encours(self.dictionnaire["salle"]["url_plan"],self.ech)
                            element["shape"] = "rien"
                            self.oldx = x
                            self.oldy = y
                self.actualise_image()
        else:
            self.oldx = 0
            self.oldy = 0

    def mesureEffectuee(self):
        """
        Releve de la mesure
        """
        print globals()["campagne"]
        dess3 = Dessin("")
        obj=Gestion("")    
        print globals()["campagne"]["env"], globals()["campagne"]["stattrafic"]
        if globals()["campagne"]["env"]=="1" and globals()["campagne"]["stattrafic"]=="1" :
            if(self.oldx and self.oldy):
                for element in self.ech:
                    if ((element["x_step"] == self.oldx) and (element["y_step"] == self.oldy)):
                        mesure = Mesure()
                        mesure.createByDico(self.dicoMesure())
                        cw = ConfigWifi()
                        lw = ListWifi()
                        pw = PerfWifi()
                        element["shape"] = "carre"
                        res=obj.getIwc()
                        print res
                        cw.createByDico(res)
                        element["signal"] = res["Signal level"]
                        lw.createByListeDico(obj.getIwli())
                        if globals()["campagne"]["modeiperf"] == "tcp":
                            pw.createByListeDico(obj.getIperf(self.dicoiperftcp))
                        if globals()["campagne"]["modeiperf"] == "udp":
                            pw.createByListeDico(obj.getIperf(self.dicoiperfudp))
                        if globals()["campagne"]["modeiperf"] == "tcp&udp":
                            pw.createByListeDico(obj.getIperf(self.dicoiperftcp))
                            pw.createByListeDico(obj.getIperf(self.dicoiperfudp))
                dess3.dessiner(self.dictionnaire["salle"]["url_plan"],self.ech,int(globals()["campagne"]["step"]))                    
                dess3.encours(self.dictionnaire["salle"]["url_plan"],self.ech)
                self.oldx = 0
                self.olfy = 0
                mesure.addConfigWifi(cw)
                mesure.addListWifi(lw)
                mesure.addPerfWifi(pw)
                mesure.insertToDb(globals()["campagne"]["id"])

        if globals()["campagne"]["env"]=="0" and globals()["campagne"]["stattrafic"]=="1" :
            if(self.oldx and self.oldy):
                for element in self.ech:
                    if ((element["x_step"] == self.oldx) and (element["y_step"] == self.oldy)):
                        mesure = Mesure()
                        mesure.createByDico(self.dicoMesure())
                        cw = ConfigWifi()
                        #lw = ListWifi()
                        pw = PerfWifi()
                        element["shape"] = "carre"
                        res=obj.getIwc()
                        print res
                        cw.createByDico(res)
                        element["signal"] = res["Signal level"]
                        #lw.createByListeDico(obj.getIwli())
                        if globals()["campagne"]["modeiperf"] == "tcp":
                            pw.createByListeDico(obj.getIperf(self.dicoiperftcp))
                        if globals()["campagne"]["modeiperf"] == "udp":
                            pw.createByListeDico(obj.getIperf(self.dicoiperfudp))
                        if globals()["campagne"]["modeiperf"] == "tcp&udp":
                            pw.createByListeDico(obj.getIperf(self.dicoiperftcp))
                            pw.createByListeDico(obj.getIperf(self.dicoiperfudp))
                dess3.dessiner(self.dictionnaire["salle"]["url_plan"],self.ech,int(globals()["campagne"]["step"]))                    
                dess3.encours(self.dictionnaire["salle"]["url_plan"],self.ech)
                self.oldx = 0
                self.olfy = 0
                mesure.addConfigWifi(cw)
                #mesure.addListWifi(lw)
                mesure.addPerfWifi(pw)
                mesure.insertToDb(globals()["campagne"]["id"])

        if globals()["campagne"]["env"]=="1" and globals()["campagne"]["stattrafic"]=="0" :
            if(self.oldx and self.oldy):
                for element in self.ech:
                    if ((element["x_step"] == self.oldx) and (element["y_step"] == self.oldy)):
                        mesure = Mesure()
                        mesure.createByDico(self.dicoMesure())
                        cw = ConfigWifi()
                        lw = ListWifi()
                        #pw = PerfWifi()
                        element["shape"] = "carre"
                        res=obj.getIwc()
                        print res
                        cw.createByDico(res)
                        element["signal"] = res["Signal level"]
                        lw.createByListeDico(obj.getIwli())
                        #pw.createByListeDico(obj.getIperf(self.dicoiperftcp))
                        dess3.dessiner(    self.dictionnaire["salle"]["url_plan"],self.ech,int(globals()["campagne"]["step"]))                    
                        dess3.encours(self.dictionnaire["salle"]["url_plan"],self.ech)
                        self.oldx = 0
                        self.olfy = 0
                        mesure.addConfigWifi(cw)
                        mesure.addListWifi(lw)
                        #mesure.addPerfWifi(pw)
                        mesure.insertToDb(globals()["campagne"]["id"])

        if globals()["campagne"]["env"]=="0" and globals()["campagne"]["stattrafic"]=="0" :
            if(self.oldx and self.oldy):
                for element in self.ech:
                    if ((element["x_step"] == self.oldx) and (element["y_step"] == self.oldy)):
                        mesure = Mesure()
                        mesure.createByDico(self.dicoMesure())
                        cw = ConfigWifi()
                        #lw = ListWifi()
                        #pw = PerfWifi()
                        element["shape"] = "carre"
                        res=obj.getIwc()
                        print res
                        cw.createByDico(res)
                        element["signal"] = res["Signal level"]
                        #lw.createByListeDico(obj.getIwli())
                        #pw.createByListeDico(obj.getIperf(self.dicoiperftcp))
                        dess3.dessiner(    self.dictionnaire["salle"]["url_plan"],self.ech,int(globals()["campagne"]["step"]))                    
                        dess3.encours(self.dictionnaire["salle"]["url_plan"],self.ech)
                        self.oldx = 0
                        self.olfy = 0
                        mesure.addConfigWifi(cw)
                        #mesure.addListWifi(lw)
                        #mesure.addPerfWifi(pw)
                        mesure.insertToDb(globals()["campagne"]["id"])

        self.actualise_image()
        self.nbMesure=self.nbMesure+1

    def dicoMesure(self):
        """
        Definition du dictionnaire des mesures
        """
        dico = {}
        dico["description"]     =  self.lineEdit_situationgeo.displayText()
        dico["x"]         =  self.comboBox_X.currentText()
        dico["y"]         =  self.comboBox_Y.currentText()
        dico["z"]         =  self.comboBox_Z.currentText()
#TODO: originale method: toPlaintext()
        dico["time"]         =  self.lineEdit_duree_mesure.displayText()
        return dico


    def setupUi(self, Dialog):
        """
        Definition de l'interface graphique.
        La majorite de cette fonction est decrite dans le fichier genere par pyuic4 dans PythonUI/...
        """
        Ui_Page7.setupUi(self,Dialog)        
        self.comboBox_X.addItem("...")
        self.comboBox_Y.addItem("...")
        self.comboBox_Z.addItem("...")        
        if(int(self.dicocampagne["manuel"])):
            print "manuel"
            self.comboBox_X.setEditable(True)
            self.comboBox_X.setDuplicatesEnabled(False)
            self.comboBox_Y.setEditable(True)            
            self.comboBox_Y.setDuplicatesEnabled(False)
            self.comboBox_Z.setEditable(True)
            self.comboBox_Z.setDuplicatesEnabled(False)
#        self.label_plan.setPixmap(QtGui.QPixmap.fromImage(dicosalle['url_plan']))
        self.calculCoord()
        for element in self.ech:
            if (self.comboBox_X.findText(str(element["x_step"]),Qt.MatchExactly) == -1):
                self.comboBox_X.addItem(str(element["x_step"]))
            if (self.comboBox_Y.findText(str(element["y_step"]),Qt.MatchExactly) == -1):
                self.comboBox_Y.addItem(str(element["y_step"]))
        #Raccourci clavier -> F6: lancer la mesure, F7: arreter la mesure, F8: point suivant
        self.pushButton_lancer.setShortcut('F6')
        self.pushButton_passer.setShortcut('F7')
        self.pushButton_next.setShortcut('F8')
        self.comboBox_Z.addItem("0")
        #Affichage du repere
        self.repere = QtGui.QImage("../images/pointeur1.png")
        self.repereModif = self.repere.scaled(60,60,Qt.KeepAspectRatio,Qt.FastTransformation)
        self.label_axe.clear()
	self.label_axe.setPixmap(QtGui.QPixmap.fromImage(self.repereModif))
        #Signaux
        self.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), self.suivant)
        self.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), self.precedent)
        self.connect(self.pushButton_lancer, QtCore.SIGNAL("clicked()"), self.mesureEffectuee)
        self.connect(self.pushButton_passer, QtCore.SIGNAL("clicked()"), self.avance)
        self.connect(self.pushButton_next, QtCore.SIGNAL("clicked()"), self.avance)
        self.connect(self.comboBox_X, QtCore.SIGNAL("currentIndexChanged(int)"), self.miseAJour)
        self.connect(self.comboBox_Y, QtCore.SIGNAL("currentIndexChanged(int)"), self.miseAJour)
        self.connect(self.comboBox_Z, QtCore.SIGNAL("currentIndexChanged(int)"), self.miseAJour)
        QtCore.QMetaObject.connectSlotsByName(Dialog)
